package com.threeti.mecool.web.controller.report;

import com.threeti.mecool.core.application.report.ReportService;
import com.threeti.mecool.core.application.report.SellIntoRate;
import com.threeti.mecool.core.domain.model.basicdata.AdminDivisionLevelDeep;
import com.threeti.mecool.core.domain.model.basicdata.biz.MeCoolAdminDivisionAreaRegistry;
import com.threeti.mecool.core.domain.model.project.ProjectStatus;
import com.threeti.mecool.core.domain.model.project.ProjectStore;
import com.threeti.mecool.core.domain.model.sellinto.SellInto;
import com.threeti.mecool.core.domain.model.sellinto.SellIntoStatus;
import com.threeti.mecool.core.infrastructure.persistence.SellIntoRepository;
import com.threeti.mecool.core.infrastructure.persistence.project.ProjectStoreRepository;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.legacy.domain.model.basicdata.AdminDivisionLegacy;
import com.threeti.mecool.legacy.infrastructure.persistence.AdminDivisionLegacyRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.ListIterator;
import java.util.Map;

@Controller
@RequestMapping("/report/sellIntoRate")
public class SellIntoRateReportController {
    private static final Logger logger = LoggerFactory.getLogger(SellIntoRateReportController.class);

    //<editor-fold desc="fields">
    @Autowired
    private ProjectStoreRepository projStoreRepo;

    @Autowired
    private SellIntoRepository sellIntoRepository;

    @Autowired
    private ReportService rptService;

    @Autowired
    private AdminDivisionLegacyRepository adminDivLegRepo;
    //</editor-fold>

    @RequestMapping(value = "/reportList/{adminDivLevelDeep}.html")
    public String reportList(@PathVariable int adminDivLevelDeep, Map modelMap) {
        modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
        return "/report/sellIntoRate/reportList";
    }

    @RequestMapping(value = "/reportList/6/{customAdminDivAreaCode}.html")
    public String reportList1(@PathVariable String customAdminDivAreaCode, Map modelMap) {
        modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal());
        modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);

        return "/report/sellIntoRate/reportList";
    }

    @RequestMapping(value = "/reportList/1/{standardAdminDivAreaCode}.html")
    public String reportList2(@PathVariable String standardAdminDivAreaCode, Map modelMap) {

        //将异步操作转化为同步操作以满足地图绘制...
        List<SellIntoRate> rates = rptService.sellIntoRateSummaryByProvince(standardAdminDivAreaCode);
        boolean isAreaNameSpecial = false;

        if (!CollectionUtils.isEmpty(rates)) {
            String tryingFirstRateAreaName = rates.get(0).getAdminDivAreaName();

            //收到继续向下钻取的信号(目前即钻取至最明细级别的数据)
            if (isAreaNameSpecial = MeCoolAdminDivisionAreaRegistry.isAreaNameSpecial(tryingFirstRateAreaName)) {
                rates = rptService.sellIntoRateSummaryByCity(standardAdminDivAreaCode);
            }
        }

        modelMap.put("sellIntoRates", rates);//汇总数据

        //TODO jay:过于简单粗暴的处理方式，为了避免设置'城市or省市'这个标志位，处理为先根据城市查询,获取不到则尝试再获取省市数据，本处理差不多是以浪费一次查询为代价的
        //TODO jay:Extract service and method...
        List<ProjectStore> plannedStoresDetail;
        List<SellInto> actualRefStoresDetail;
        List<ProjectStore> actualStoresDetail = Lists.newArrayList();
        try {
            plannedStoresDetail = projStoreRepo.findByProjectStatusAndChannel_Channel_CityAdCode(ProjectStatus.ACTIVE, standardAdminDivAreaCode);
            actualRefStoresDetail = sellIntoRepository.findByStatusAndProjectStore_Channel_Channel_CityAdCode(SellIntoStatus.SUCCESS, standardAdminDivAreaCode);

            if (CollectionUtils.isEmpty(plannedStoresDetail)) {
                plannedStoresDetail = projStoreRepo.findByProjectStatusAndChannel_Channel_ProvinceAdCode(ProjectStatus.ACTIVE, standardAdminDivAreaCode);
                actualRefStoresDetail = sellIntoRepository.findByStatusAndProjectStore_Channel_Channel_ProvinceAdCode(SellIntoStatus.SUCCESS, standardAdminDivAreaCode);

                //计划门店和实际门店均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
                if (CollectionUtils.isEmpty(plannedStoresDetail)) {
                    AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
                    String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentProvinceAdName()) ? adminDivLeg.getName() : adminDivLeg.getParentProvinceAdName();
                    modelMap.put("standardAdminDivAreaName", provinceAdName);
                } else {
                    modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getChannel().getProvinceAdName());
                }
                //<-
                if (isAreaNameSpecial) {//发现特殊地域名的，强制视为已经进入特定城市内部
                    modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
                    modelMap.put("mapZoomLevel", "13");//8是一个相对合适的用于省市级别展示的ZOOM等级
                } else {
                    modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.CITY.ordinal());
                    modelMap.put("mapZoomLevel", "8");//8是一个相对合适的用于省市级别展示的ZOOM等级
                }

                for (SellInto actualResult : actualRefStoresDetail) {
                    for (ListIterator<ProjectStore> iter = plannedStoresDetail.listIterator(); iter.hasNext(); ) {
                        ProjectStore projStore = iter.next();
                        if (actualResult.getProjectStore().getChannelCode().equals(projStore.getChannel().getCode())) {
                            actualStoresDetail.add(projStore);//把当前门店加入实际开店列表，表示该门店已实际开店
                            iter.remove();//从计划门店列表中移除当前门店
                        }
                    }
                }
            } else {
                modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
                modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getChannel().getCityAdName());
                modelMap.put("mapZoomLevel", "13");//13是一个相对合适的用于城区级别展示的ZOOM等级

                for (SellInto actualResult : actualRefStoresDetail) {
                    for (ListIterator<ProjectStore> iter = plannedStoresDetail.listIterator(); iter.hasNext(); ) {
                        ProjectStore projStore = iter.next();
                        if (actualResult.getProjectStore().getChannelCode().equals(projStore.getChannel().getCode())) {
                            actualStoresDetail.add(projStore);//把当前门店加入实际开店列表，表示该门店已实际开店
                            iter.remove();//从计划门店列表中移除当前门店
                        }
                    }
                }
            }

            //明细数据
            modelMap.put("actualStoresDetail", actualStoresDetail);
            modelMap.put("plannedStoresDetail", plannedStoresDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //<-
        modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);
        return "/report/sellIntoRate/reportListCityMap";
    }

    @RequestMapping(value = "/reportList/2/{standardAdminDivAreaCode}.html")
    public String reportList3(@PathVariable String standardAdminDivAreaCode, Map modelMap) {
        List<SellIntoRate> rates = rptService.sellIntoRateSummaryByCity(standardAdminDivAreaCode);

        modelMap.put("sellIntoRates", rates);//汇总数据
        modelMap.put("mapZoomLevel", "13");//13是一个相对合适的用于城区级别展示的ZOOM等级
        modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());

        try {
            List<ProjectStore> plannedStoresDetail;
            List<SellInto> actualRefStoresDetail;
            List<ProjectStore> actualStoresDetail = Lists.newArrayList();

            plannedStoresDetail = projStoreRepo.findByProjectStatusAndChannel_Channel_CityAdCode(ProjectStatus.ACTIVE, standardAdminDivAreaCode);
            actualRefStoresDetail = sellIntoRepository.findByStatusAndProjectStore_Channel_Channel_CityAdCode(SellIntoStatus.SUCCESS, standardAdminDivAreaCode);

            //计划门店和实际门店均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
            if (CollectionUtils.isEmpty(plannedStoresDetail)) {
                AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
                String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName() : adminDivLeg.getParentCityAdName();
                modelMap.put("standardAdminDivAreaName", provinceAdName);
            } else {
                modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getChannel().getCityAdName());
            }
            //<-

            for (SellInto actualResult : actualRefStoresDetail) {
                for (ListIterator<ProjectStore> iter = plannedStoresDetail.listIterator(); iter.hasNext(); ) {
                    ProjectStore projStore = iter.next();
                    if (actualResult.getProjectStore().getChannelCode().equals(projStore.getChannel().getCode())) {
                        actualStoresDetail.add(projStore);//把当前门店加入实际开店列表，表示该门店已实际开店
                        iter.remove();//从计划门店列表中移除当前门店
                    }
                }
            }

            //明细数据
            modelMap.put("actualStoresDetail", actualStoresDetail);
            modelMap.put("plannedStoresDetail", plannedStoresDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }

        modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);

        return "/report/sellIntoRate/reportListCityMap";
    }

    @RequestMapping(value = "/reportList/3/{standardAdminDivAreaCode}.html")
    public String reportList7(@PathVariable String standardAdminDivAreaCode, Map modelMap) {
        List<SellIntoRate> rates = rptService.sellIntoRateSummaryByCity(standardAdminDivAreaCode);

        modelMap.put("sellIntoRates", rates);//汇总数据
        modelMap.put("mapZoomLevel", "13");//13是一个相对合适的用于城区级别展示的ZOOM等级
        modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.SELL_IN.ordinal());

        try {
            List<ProjectStore> plannedStoresDetail;
            List<SellInto> actualRefStoresDetail;
            List<ProjectStore> actualStoresDetail = Lists.newArrayList();

            plannedStoresDetail = projStoreRepo.findByProjectStatusAndChannel_Channel_AdCode(ProjectStatus.ACTIVE, standardAdminDivAreaCode);
            actualRefStoresDetail = sellIntoRepository.findByStatusAndProjectStore_Channel_Channel_AdCode(SellIntoStatus.SUCCESS, standardAdminDivAreaCode);
            modelMap.put("sellInto", sellIntoRepository.findByProjectStore_Channel_Channel_AdCode(standardAdminDivAreaCode));
            //计划门店和实际门店均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
            if (CollectionUtils.isEmpty(plannedStoresDetail)) {
                AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
                String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName() : adminDivLeg.getParentCityAdName();
                modelMap.put("standardAdminDivAreaName", provinceAdName);
            } else {
                modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getChannel().getCityAdName());
            }
            //<-

            for (SellInto actualResult : actualRefStoresDetail) {
                for (ListIterator<ProjectStore> iter = plannedStoresDetail.listIterator(); iter.hasNext(); ) {
                    ProjectStore projStore = iter.next();
                    if (actualResult.getProjectStore().getChannelCode().equals(projStore.getChannel().getCode())) {
                        actualStoresDetail.add(projStore);//把当前门店加入实际开店列表，表示该门店已实际开店
                        iter.remove();//从计划门店列表中移除当前门店
                    }
                }
            }

            //明细数据
            modelMap.put("actualStoresDetail", actualStoresDetail);
            modelMap.put("plannedStoresDetail", plannedStoresDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }

        modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);

        return "/report/sellIntoRate/reportListCityMap";
    }

    @RequestMapping(value = "/reportListData/{adminDivLevelDeep}.html")
    public String reportListData(@PathVariable int adminDivLevelDeep, Map modelMap) {
        List<SellIntoRate> rates = Lists.newArrayList();
        if (adminDivLevelDeep == AdminDivisionLevelDeep.NATIONWIDE.ordinal()) {
            rates.add(rptService.sellIntoRateSummaryByCountry());
        } else if (adminDivLevelDeep == AdminDivisionLevelDeep.PROVINCE.ordinal()) {
            rates = rptService.sellIntoRateSummaryByProvinceALL();
            modelMap.put("sellIntoRatesNationwide", rptService.sellIntoRateSummaryByCountry());
        } else if (adminDivLevelDeep == AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal()) {
            rates = rptService.sellIntoRateSummaryByCustomAreas();
        }
        modelMap.put("sellIntoRates", rates);
        modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
        return "/report/sellIntoRate/reportListData";
    }

    @RequestMapping(value = "/reportListData/6/{customAdminDivAreaCode}.html")
    public String reportListData1(@PathVariable String customAdminDivAreaCode, Map modelMap) {
        List<SellIntoRate> rates = rptService.sellIntoRateSummaryByCustomArea(customAdminDivAreaCode);

        modelMap.put("sellIntoRates", rates);
        modelMap.put("adminDivLevelDeep", AdminDivisionLevelDeep.PROVINCE.ordinal());
        modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);

        return "/report/sellIntoRate/reportListData";
    }
}
